﻿#include "audiodecode.h"

#include "qtlog.h"

AudioDecode::AudioDecode(QObject *parent) : QObject(parent)
{

}

AudioDecode::~AudioDecode()
{

}

void AudioDecode::Stop()
{
    QMutexLocker lock(&mutex);
    if (output)
        {
            output->stop();
            delete output;
            output = nullptr;
            io = nullptr;
        }
}

#define MAX_AUDIO_FRAME_SIZE_HIGH 320000

bool AudioDecode::Start()
{
    Stop();
    QMutexLocker lock(&mutex);
    QAudioFormat fmt; //Qt音频的格式

    fmt.setSampleRate(this->sampleRate); //1秒采集48000个声音
    fmt.setSampleSize(16); //16位
    fmt.setChannelCount(this->channel);  //声道2双声道
    fmt.setCodec("audio/pcm");           //音频的格式
    fmt.setByteOrder(QAudioFormat::LittleEndian); //次序
    fmt.setSampleType(QAudioFormat::SignedInt); //样本的类别


    if(!QAudioDeviceInfo(QAudioDeviceInfo::defaultOutputDevice()).isFormatSupported(fmt))
    {
        fprintf(stderr,"Not a supported audio format.\n");
        return -1;
    }
//    audio_out.sample_fmt = AV_SAMPLE_FMT_S16;
//    audio_out.nb_samples = iAcc->frame_size;
//    audio_out.channel_layout = AV_CH_LAYOUT_STEREO;
//    audio_out.sample_rate = 44100;
//    audio_out.channels = av_get_channel_layout_nb_channels(audio_out.channel_layout);


    output = new QAudioOutput(fmt);
    output->setBufferSize(this->sampleRate*this->channel*this->sampleSize/8);
    io = output->start();
    return true;
}

void AudioDecode::Play(bool isPlay)
{
    QMutexLocker lock(&mutex);
    if (!output)
    {
        return;
    }

    if (isPlay)
    {
        output->resume();
    }
    else
    {
        output->suspend();
    }
}

bool AudioDecode::Write(const char *data, int datasize)
{
    QMutexLocker lock(&mutex);

    if (!data || datasize <= 0)
            return false;
    if (io)
    {
        io->write(data, datasize);
        return true;
    }
    return false;
}

int AudioDecode::GetFree()
{
    QMutexLocker lock(&mutex);
    if (!output)
    {
        mutex.unlock();
        return 0;
    }

    int free = output->bytesFree();
    return free;
}

void AudioDecode::setSample(int _sampleRate, int _sampleSize, int _channel)
{
    sampleRate = _sampleRate;
    sampleSize = _sampleSize;
    channel = _channel;
    qDLog()<<"sampleRate:"<<_sampleRate<<"_sampleSize:"<<_sampleSize<<"_channel:"<<_channel;
}

void AudioDecode::s_audio(QByteArray bt)
{
    Write(bt.data(),bt.size());
}

